import axios from 'axios'
import qs from 'qs'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import {
  getToken
} from '@/utils/auth'
import router from '../router'

axios.defaults.baseURL = process.env.VUE_APP_BASE_API
console.log("axios.defaults", axios.defaults)
console.log("process.env", process.env)
axios.defaults.withCredentials = true
axios.defaults.timeout = 5000

// create an axios instance
// const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   // withCredentials: true, // send cookies when cross-domain requests
//   timeout: 5000 // request timeout
// })

const axiosConfig = {
  headers: {
    post: {
      "Content-Type": "application/json" //application/json;charset=UTF-8
    },
    get: {
      "Content-Type": "application/x-www-form-urlencoded"
    }
  },
  timeout: 10000 * 10
};
Object.assign(axios.defaults, axiosConfig);

// request interceptor
axios.interceptors.request.use(
  config => {
    // 请求之前拦截
    if (store.getters.token) {
      // 在请求之前设置请求头
      config.headers['Authorization'] = getToken()
      config.headers['tokenId'] = localStorage.getItem("accountId")
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
axios.interceptors.response.use(
  // 请求成功后拦截
  response => {
    const res = response.data

    if (res.code !== 200 && res.code !== "2000") {
      Message({
        message: res.message || "error",
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))

    } else if (res.code === 402) {
      Message({
        message: "登录过期, 请重新登录",
        type: 'error',
        duration: 5 * 1000
      })
      let path = location.hash
      path = path.split("#")[1]
      router.push({
        path: "/login?redirect=" + path
      })
    } else {

      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default {
  config: {
    user: process.env.VUE_APP_BASE_USER,
    auth: process.env.VUE_APP_BASE_AUTH,
    wallet: process.env.VUE_APP_BASE_WALLET,
    log: process.env.VUE_APP_BASE_LOG,
    sm: process.env.VUE_APP_BASE_SM,
    json: process.env.VUE_APP_BASE_JSON,
    coin: process.env.VUE_APP_BASE_COIN,
    base: process.env.VUE_APP_BASE_BASE
  },
  get(url, params, headers) {

    let queryConfig = {
      method: "get",
      url: `${url}`,
      params: params
    };

    if (headers) {
      queryConfig["headers"] = { ...headers};
    }
    return axios(queryConfig);
  },
  post(url, params, headers) {
    console.log("url", url)
    let queryConfig = {
      method: "post",
      url: `${url}`,
      params: params,
      paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
      }
    };
    if (headers) {
      queryConfig["headers"] = { ...headers};
    }
    return axios(queryConfig);
  },
  put(url, params, headers) {
    let queryConfig = {
      method: "put",
      url: `${url}`,
      params: params,
      paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
      }
    };
    if (headers) {
      queryConfig["headers"] = { ...headers};
    }
    return axios(queryConfig);
  },
  del() {
    let queryConfig = {
      method: "del",
      url: `${url}`,
    };
    if (headers) {
      queryConfig["headers"] = { ...headers};
    }
    return axios(queryConfig);
  }
}
